package de.zainodis.triplog.ui.fragment;

/**
 * Created by fzarrai on 8/10/2014.
 */

import android.accounts.Account;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.Date;

import de.zainodis.triplog.data.DataProvider;
import de.zainodis.triplog.data.LocationEntry;
import de.zainodis.triplog.data.persistence.IWeatherDao;
import de.zainodis.triplog.data.share.TriplogContract;
import de.zainodis.triplog.data.share.WeatherProvider;
import de.zainodis.triplog.ui.WeatherForecastAdapter;
import de.zainodis.triplog.ui.task.IWeatherForecastActions;
import de.zainodis.triplog.util.DateTimeUtils;


/**
 * Displays a list of weather forecast items.
 */
public class ForecastFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, IForecastList {
    private static final String TAG = "ForecastFragment";
    private static final String BUNDLE_POSITION = "LastPosition";
    private int lastPosition = 0;

    /**
     * Each loader has an ID, which allows for several loaders running at the same time.
     */
    private static final int FORECAST_LOADER_ID = 0;
    public static final int NUMBER_OF_DAYS = 10;
    private WeatherForecastAdapter adapter;

    // Instance fields
    Account syncAccount;

    private static final String[] FORECAST_COLUMNS = {
            /*We need to provide a fully qualified id for the weather table */
            IWeatherDao.TABLE_NAME + "." + IWeatherDao.COLUMN_ID,
            IWeatherDao.COLUMN_DATETEXT,
            IWeatherDao.COLUMN_DESCRIPTION,
            IWeatherDao.COLUMN_MAX_TEMP,
            IWeatherDao.COLUMN_MIN_TEMP,
            IWeatherDao.COLUMN_WEATHER_ICON_ID
    };

    /*Matching indices for  FORECAST_COLUMNS projection */
    public static final int COLUMN_ID = 0;
    public static final int COLUMN_DATE = 1;
    public static final int COLUMN_DESCRIPTION = 2;
    public static final int COLUMN_MAX_TEMP = 3;
    public static final int COLUMN_MIN_TEMP = 4;
    public static final int COLUMN_ICON_ID = 5;

    IWeatherForecastActions callback;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            callback = (IWeatherForecastActions) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement IWeatherForecastActions");
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        //We initialize the loader here which is bound to the activity lifecycle
        getLoaderManager().initLoader(FORECAST_LOADER_ID, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //Restore last position
            lastPosition = savedInstanceState.getInt(BUNDLE_POSITION, 0);
        }
        adapter = new WeatherForecastAdapter(getActivity(), null, 0);
        setListAdapter(adapter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(BUNDLE_POSITION, lastPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        lastPosition = position;
        Cursor cursor = adapter.getCursor();
        if (cursor != null && cursor.moveToPosition(position)) {
            //Obtain the row id
            int rowId = cursor.getInt(COLUMN_ID);
            callback.displayForecastDetails(rowId);
        }
    }

    @Override
    public void setIsDualPane(boolean isDualPane) {
        if (adapter != null) {
            adapter.setIsDualPane(isDualPane);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        //Get Current location
        LocationEntry location = DataProvider.getCurrentTrip().getLocation();
        //Filter by date starting from today (we don't care about yesterdays weather)
        String startDate = DateTimeUtils.toDbDateString(new Date());
        //Sort in ascending order (by date)
        String sortOrder = IWeatherDao.COLUMN_DATETEXT + " ASC";
        String select = WeatherProvider.WEATHER_FORECAST_SELECTION;
        String[] arguments = {String.valueOf(location.getId()), startDate};
        Uri forecastUri = TriplogContract.CONTENT_URI_WEATHER;
        return new CursorLoader(getActivity(), forecastUri, FORECAST_COLUMNS, select, arguments, sortOrder);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        adapter.swapCursor(data);
        //Restore position
        getListView().smoothScrollToPosition(lastPosition);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        adapter.swapCursor(null);
    }

}

